<script setup lang="ts">
import type { UploadCustomRequestOptions, UploadFileInfo } from 'naive-ui'
import { uploadLocal } from '@/utils/localOss'
type PropsState = {
  directory?: string
}
const props = withDefaults(defineProps<PropsState>(), {})
const url = defineModel<string>({
  required: false,
  default: '',
})
const size = defineModel<number>('size', {
  required: false,
  default: 0,
})

const fileList = ref<UploadFileInfo[]>([])

const customRequest = (options: UploadCustomRequestOptions) => {
  uploadLocal(options, props.directory)
}
const beforeUpload = async (data: { file: UploadFileInfo; fileList: UploadFileInfo[] }) => {
  const maxSize = import.meta.env.VITE_UPLOAD_IMAGE_MAX_SIZE
  if (data.file.file?.size && data.file.file.size >= maxSize * 1024 * 1024) {
    msgUtil.$message.error('上传文件大小不能超过' + maxSize + 'MB，请重新上传')
    return false
  }
  return true
}
const handFinish = (e) => {
  url.value = e.file.url
  size.value = e.file.file.size
}
const init = () => {
  const status = fileList.value.some((el) => el.url === url.value)
  if (!status) {
    nextTick(() => {
      const arr = url.value.split('/')
      const fileName = arr[arr.length - 1]
      fileList.value = [
        {
          id: fileName,
          name: fileName,
          url: url.value,
          thumbnailUrl: url.value,
          status: 'finished',
        },
      ]
    })
  }
}
const handReset = () => {
  fileList.value = []
  url.value = ''
  size.value = 0
}
watch(
  url,
  (newVal) => {
    if (newVal) {
      init()
    } else {
      handReset()
    }
  },
  {
    immediate: true,
  },
)
</script>

<template>
  <n-upload
    action=""
    v-model:file-list="fileList"
    accept="image/*"
    list-type="image-card"
    :max="1"
    showPreviewButton
    :custom-request="customRequest"
    @before-upload="beforeUpload"
    @remove="handReset"
    @finish="handFinish"
  />
</template>

<style scoped lang="scss"></style>
